package com.example.mycontact

import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.ContextMenu
import android.view.MenuItem
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.example.mycontact.DB.ContactTable
import com.example.mycontact.adapter.MyContactAdapter
import com.example.mycontact.bean.Contact
import com.example.mycontact.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    var specialFavoritesList = ArrayList<Contact>()  // 特别关注列表
    var otherContactsList = ArrayList<Contact>()    // 其余联系人列表
    lateinit var contactTable: ContactTable
    lateinit var binding: ActivityMainBinding
    var currentContactView: View? = null  // 存储当前长按的视图
    lateinit var sharedPreferences: SharedPreferences
    private val SEARCH_HISTORY_KEY = "search_history"
    private val MAX_HISTORY_COUNT = 3
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //视图加载，绑定布局
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        // 初始化SharedPreferences用于存储搜索历史
        sharedPreferences = getSharedPreferences("contact_app", MODE_PRIVATE)
        // 加载搜索历史
        loadSearchHistory()
        binding.btnAdd.setOnClickListener {
            //跳转到添加联系人界面
            val intent = Intent(this,AddContactActivity::class.java)
            startActivity(intent)
        }
        
        binding.btnRandom.setOnClickListener {
            //随机选择联系人
            selectRandomContact()
        }
        
        // 设置搜索历史点击事件
        binding.tvHistory1.setOnClickListener {
            searchByHistory(binding.tvHistory1.text.toString())
        }
        binding.tvHistory2.setOnClickListener {
            searchByHistory(binding.tvHistory2.text.toString())
        }
        binding.tvHistory3.setOnClickListener {
            searchByHistory(binding.tvHistory3.text.toString())
        }
        //ListView加载数据
        //1.准备数据 从数据表中查询出来ArrayList<Contact>
        contactTable = ContactTable(this)
        loadGroupedContacts()

        //查找联系人 模糊查询
        binding.etSearch.addTextChangedListener(object: TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                //输入框文本发生改变时
                //根据输入的条件实施查询显示
                val inputKey = binding.etSearch.text.toString()
                if (inputKey.isBlank()) {
                    // 搜索框为空，恢复显示全部联系人（分组）
                    binding.tvOtherContacts.text = "所有联系人"
                    binding.tvSpecialFavorite.text = "常用联系人"
                    loadGroupedContacts()
                    binding.llSearchHistory.visibility = if (hasSearchHistory()) View.VISIBLE else View.GONE
                } else {
                    // 有搜索关键字，显示过滤结果
                    showSearchMode(inputKey)
                    // 隐藏搜索历史
                    binding.llSearchHistory.visibility = View.GONE
                }
            }

            override fun afterTextChanged(s: Editable?) {

            }

        })
        // 注册上下文菜单需要在手动创建视图后调用
    }

    override fun onCreateContextMenu(
        menu: ContextMenu?,
        v: View?,
        menuInfo: ContextMenu.ContextMenuInfo?
    ) {
        // 存储当前点击的视图
        currentContactView = v
        val contact = v?.tag as? Contact
        
        menuInflater.inflate(R.menu.menu_listview_context, menu)
        
        // 设置菜单标题显示联系人信息
        menu?.setHeaderTitle(contact?.name ?: "未知联系人")
        
        super.onCreateContextMenu(menu, v, menuInfo)
    }
    
    // 从View中获取联系人信息
    private fun getContactFromView(view: View?): String {
        val nameText = view?.findViewById<TextView>(R.id.list_item_tv_name)
        return nameText?.text?.toString() ?: "未知联系人"
    }

    override fun onContextItemSelected(item: MenuItem): Boolean {
        // 全局变量存储当前点击的联系人视图
        val clickedContactView: View? = currentContactView
        
        // 从View标签中获取联系人
        val selectContact = clickedContactView?.tag as? Contact
        
        selectContact?.let { contact ->
            when(item?.itemId){
                R.id.m_c_lv_delete -> {
                    //删除联系人 - 弹出确认对话框
                    val builder = AlertDialog.Builder(this)
                    builder.setTitle("确认删除")
                    builder.setMessage("确定要删除联系人 \"${contact.name}\" 吗？此操作无法撤销。")
                    builder.setPositiveButton("确认") { dialog, which ->
                        //用户点击确认删除
                        if(contactTable.deleteContactById(contact.id)){
                            Toast.makeText(this,"删除成功",Toast.LENGTH_SHORT).show()
                            loadGroupedContacts() // 重新加载分组数据
                        }else{
                            Toast.makeText(this,"删除失败",Toast.LENGTH_SHORT).show()
                        }
                    }
                    builder.setNegativeButton("取消") { dialog, which ->
                        //用户点击取消，什么都不做
                    }
                    builder.show()
                }
                R.id.m_c_lv_update -> {
                    //修改联系人
                    //获取当前点击的item的id
                    val intent = Intent(this, UpdateActivity::class.java)
                    intent.putExtra("updateContact", contact)
                    startActivity(intent)
                }

                else -> {

                }
            }
        }
        return true
    }
    
    // 处理从InfoActivity返回时的结果
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 100) {
            // 从联系人详情页面返回，刷新分组列表以反映关注状态的变化
            loadGroupedContacts()
        }
    }
    
    // 加载分组联系人数据
    private fun loadGroupedContacts() {
        val allContacts = contactTable.findAllContact()
        specialFavoritesList.clear()
        otherContactsList.clear()
        
        allContacts.forEach { contact ->
            if (contact.name != "没有联系人" && contact.name != "无符合条件联系人") {
                if (contact.isFavorite == 1) {
                    specialFavoritesList.add(contact)
                } else {
                    otherContactsList.add(contact)
                }
            }
        }
        // 如果完全没有联系人，显示占位提示
        if (specialFavoritesList.isEmpty() && otherContactsList.isEmpty()) {
            val placeholder = Contact()
            placeholder.name = "没有联系人"
            otherContactsList.add(placeholder)
        }
        applySorting()
        setupGroupedListViews()
    }
    
    // 设置分组联系人视图（使用 LinearLayout）
    private fun setupGroupedListViews() {
        // 确保在渲染前应用排序（按姓名 A-Z）
        applySorting()
        // 清空现有视图
        binding.llSpecialFavorites.removeAllViews()
        binding.llOtherContacts.removeAllViews()
        
        // 设置特别关注列表
        if (specialFavoritesList.isNotEmpty()) {
            binding.tvSpecialFavorite.visibility = View.VISIBLE
            binding.llSpecialFavorites.visibility = View.VISIBLE
            addContactsWithLetterHeaders(binding.llSpecialFavorites, specialFavoritesList)
        } else {
            binding.tvSpecialFavorite.visibility = View.GONE
            binding.llSpecialFavorites.visibility = View.GONE
        }
        
        // 设置其余联系人列表
        addContactsWithLetterHeaders(binding.llOtherContacts, otherContactsList)
        
        // 设置分隔线的可见性
        binding.dividerLine.visibility = if (specialFavoritesList.isNotEmpty() && otherContactsList.isNotEmpty()) {
            View.VISIBLE
        } else {
            View.GONE
        }
    }

    // 根据当前排序模式添加字母分组标题
    private fun addContactsWithLetterHeaders(container: android.widget.LinearLayout, contacts: List<Contact>) {
        var lastHeader: String? = null
        contacts.forEach { contact ->
            val isPlaceholder = contact.name == "没有联系人" || contact.name == "无符合条件联系人"
            if (!isPlaceholder) {
                val headerKey = getHeaderKey(contact)
                if (headerKey != lastHeader && headerKey.isNotEmpty()) {
                    lastHeader = headerKey
                    val headerView = TextView(this)
                    headerView.text = headerKey
                    headerView.textSize = 14f
                    headerView.setTextColor(0xFF666666.toInt())
                    headerView.setPadding(20, 16, 20, 8)
                    container.addView(headerView)
                }
            }
            val contactView = createContactView(contact)
            container.addView(contactView)
        }
    }

    private fun getHeaderKey(contact: Contact): String {
        val name = contact.name.trim()
        if (name.isEmpty()) return "#"
        return getSurnameInitial(name)
    }

    // 获取中文姓名姓氏的拼音首字母（A-Z）；英文名直接取首字母；其他返回 #
    private fun getSurnameInitial(name: String): String {
        val firstChar = getFirstMeaningfulChar(name)
        // 英文直接返回大写
        if (firstChar.isLetter()) return firstChar.uppercaseChar().toString()
        // 常见中文姓氏优先映射，避免分段误差
        val commonMap = mapOf(
            '赵' to 'Z','钱' to 'Q','孙' to 'S','李' to 'L','周' to 'Z','吴' to 'W','郑' to 'Z','王' to 'W',
            '冯' to 'F','陈' to 'C','褚' to 'C','卫' to 'W','蒋' to 'J','沈' to 'S','韩' to 'H','杨' to 'Y',
            '朱' to 'Z','秦' to 'Q','尤' to 'Y','许' to 'X','何' to 'H','吕' to 'L','施' to 'S','张' to 'Z',
            '孔' to 'K','曹' to 'C','严' to 'Y','华' to 'H','金' to 'J','魏' to 'W','陶' to 'T','姜' to 'J',
            '戚' to 'Q','谢' to 'X','邹' to 'Z','喻' to 'Y','柏' to 'B','水' to 'S','窦' to 'D','章' to 'Z',
            '云' to 'Y','苏' to 'S','潘' to 'P','葛' to 'G','范' to 'F','彭' to 'P','郎' to 'L','鲁' to 'L',
            '韦' to 'W','昌' to 'C','马' to 'M','苗' to 'M','凤' to 'F','花' to 'H','方' to 'F','俞' to 'Y',
            '任' to 'R','袁' to 'Y','柳' to 'L','酆' to 'F','鲍' to 'B','史' to 'S','唐' to 'T','费' to 'F',
            '廉' to 'L','岑' to 'C','薛' to 'X','雷' to 'L','贺' to 'H','倪' to 'N','汤' to 'T','滕' to 'T',
            '殷' to 'Y','罗' to 'L','毕' to 'B','郝' to 'H','邬' to 'W','安' to 'A','常' to 'C','乐' to 'Y',
            '于' to 'Y','时' to 'S','傅' to 'F','皮' to 'P','卞' to 'B','齐' to 'Q','康' to 'K','伍' to 'W',
            '余' to 'Y','元' to 'Y','卜' to 'B','顾' to 'G','孟' to 'M','平' to 'P','黄' to 'H','和' to 'H',
            '穆' to 'M','萧' to 'X','尹' to 'Y','姚' to 'Y','邵' to 'S','湛' to 'Z','汪' to 'W','祁' to 'Q',
            '毛' to 'M','狄' to 'D','米' to 'M','贝' to 'B','明' to 'M','臧' to 'Z','计' to 'J','伏' to 'F',
            '成' to 'C','戴' to 'D','谈' to 'T','宋' to 'S','茅' to 'M','庞' to 'P','熊' to 'X','纪' to 'J',
            '舒' to 'S','屈' to 'Q','项' to 'X','祝' to 'Z','董' to 'D','梁' to 'L','杜' to 'D','阮' to 'R',
            '蓝' to 'L','闵' to 'M','席' to 'X','季' to 'J','麻' to 'M','强' to 'Q','贾' to 'J','路' to 'L',
            '娄' to 'L','危' to 'W','江' to 'J','童' to 'T','颜' to 'Y','郭' to 'G','梅' to 'M','盛' to 'S',
            '林' to 'L','刁' to 'D','钟' to 'Z','徐' to 'X','邱' to 'Q','骆' to 'L','高' to 'G','夏' to 'X',
            '蔡' to 'C','田' to 'T','樊' to 'F','胡' to 'H','凌' to 'L','霍' to 'H','虞' to 'Y','万' to 'W',
            '支' to 'Z','柯' to 'K','昝' to 'Z','管' to 'G','卢' to 'L','莫' to 'M','房' to 'F','裘' to 'Q',
            '缪' to 'M','干' to 'G','解' to 'X','应' to 'Y','宗' to 'Z','丁' to 'D','宣' to 'X','邓' to 'D',
            '单' to 'S','杭' to 'H','洪' to 'H','包' to 'B','诸' to 'Z','左' to 'Z','石' to 'S','崔' to 'C',
            '吉' to 'J','龚' to 'G','程' to 'C','邢' to 'X','裴' to 'P','陆' to 'L','荣' to 'R','翁' to 'W'
        )
        commonMap[firstChar]?.let { return it.toString() }
        // 中文使用 GB2312 首字母表获取分段首字母
        val initial = getPinyinInitial(firstChar)
        return if (initial in 'A'..'Z') initial.toString() else "#"
    }

    private fun getFirstMeaningfulChar(text: String): Char {
        if (text.isEmpty()) return '#'
        val cleaned = text.replace("\u200B", "").trim() // 去除零宽空格等
        for (ch in cleaned) {
            if (ch.isLetter()) return ch
            if (isChinese(ch)) return ch
        }
        return cleaned.firstOrNull() ?: '#'
    }

    private fun isChinese(ch: Char): Boolean {
        return ch.code in 0x4E00..0x9FFF
    }

    // 参考 GB2312 分区来估算拼音首字母（简易近似）
    private fun getPinyinInitial(ch: Char): Char {
        return try {
            val str = ch.toString()
            val bytes = str.toByteArray(charset("GB2312"))
            if (bytes.size < 2) {
                // 非中文字符
                if (ch.isLetter()) ch.uppercaseChar() else '#'
            } else {
                val areaCode = (bytes[0].toInt() and 0xFF) * 256 + (bytes[1].toInt() and 0xFF)
                // 分段对应的首字母（不含 I、U、V）
                val initials = charArrayOf(
                    'A','B','C','D','E','F','G','H','J','K','L','M','N','O','P','Q','R','S','T','W','X','Y','Z'
                )
                val ranges = intArrayOf(
                    45217, 45253, 45761, 46318, 46826, 47010, 47297, 47614,
                    48119, 49062, 49324, 49896, 50371, 50614, 50622, 50906,
                    51387, 51446, 52218, 52698, 52980, 53689, 54481
                )
                for (i in 0 until initials.size) {
                    val start = ranges[i]
                    val end = if (i == initials.size - 1) 55290 else ranges[i + 1]
                    if (areaCode in start until end) return initials[i]
                }
                '#'
            }
        } catch (e: Exception) {
            '#'
        }
    }

    private fun applySorting() {
        // 先按姓氏首字母（A-Z），再按姓名的字母序（中文按拼音首字母序列近似）
        val comparator = Comparator<Contact> { a, b ->
            val ia = getSurnameInitial(a.name)
            val ib = getSurnameInitial(b.name)
            val c = ia.compareTo(ib)
            if (c != 0) return@Comparator c
            val ka = getNameInitials(a.name)
            val kb = getNameInitials(b.name)
            ka.compareTo(kb)
        }
        specialFavoritesList.sortWith(stableComparator(comparator))
        otherContactsList.sortWith(stableComparator(comparator))
    }

    // 将姓名转换为用于排序的“字母序”键：
    // 中文字符 -> 拼音首字母（近似，GB2312分段），字母 -> 大写字母，其它 -> '#'
    private fun getNameInitials(name: String): String {
        val cleaned = name.replace("\u200B", "").trim()
        if (cleaned.isEmpty()) return "#"
        val sb = StringBuilder()
        cleaned.forEach { ch ->
            when {
                ch.isLetter() -> sb.append(ch.uppercaseChar())
                isChinese(ch) -> sb.append(getPinyinInitial(ch))
                ch.isDigit() -> sb.append(ch)
                else -> sb.append('#')
            }
        }
        return sb.toString()
    }

    // Kotlin 的 sortWith 是稳定排序，但不同平台实现差异可能导致相等元素重排。
    // 包一层比较器，确保相等时返回 0，从而尽量保持原顺序。
    private fun <T> stableComparator(base: Comparator<T>): Comparator<T> {
        return Comparator { x, y -> base.compare(x, y) }
    }
    
    // 创建联系人视图
    private fun createContactView(contact: Contact): View {
        val layoutInflater = layoutInflater
        val contactView = layoutInflater.inflate(R.layout.activity_main_list_item, null)
        
        // 设置数据
        val tvName = contactView.findViewById<TextView>(R.id.list_item_tv_name)
        val tvCompany = contactView.findViewById<TextView>(R.id.list_item_tv_company)
        val tvPosition = contactView.findViewById<TextView>(R.id.list_item_tv_position)

        tvName.text = contact.name
        tvCompany.text = contact.company
        tvPosition.text = contact.position

        val isPlaceholder = contact.name == "没有联系人" || contact.name == "无符合条件联系人"

        if (isPlaceholder) {
            // 仅显示提示文字，不可点击，不显示其他字段
            tvCompany.visibility = View.GONE
            tvPosition.visibility = View.GONE
            contactView.isClickable = false
            contactView.isLongClickable = false
        } else {
            // 设置标签存储联系人对象
            contactView.tag = contact
            // 设置点击监听
            contactView.setOnClickListener {
                openContactDetail(contact)
            }
            // 设置长按监听并注册上下文菜单
            registerForContextMenu(contactView)
        }
        
        return contactView
    }
    
    // 显示分组模式
    private fun showGroupedMode() {
        binding.tvSpecialFavorite.visibility = if (specialFavoritesList.isNotEmpty()) View.VISIBLE else View.GONE
        binding.llSpecialFavorites.visibility = if (specialFavoritesList.isNotEmpty()) View.VISIBLE else View.GONE
        binding.tvOtherContacts.visibility = View.VISIBLE
        binding.llOtherContacts.visibility = View.VISIBLE
        
        setupGroupedListViews()
    }
    
    // 显示搜索模式
    private fun showSearchMode(searchKey: String) {
        // 隐藏分组标题和分隔线
        binding.tvSpecialFavorite.visibility = View.GONE
        binding.llSpecialFavorites.visibility = View.GONE
        binding.tvOtherContacts.visibility = View.GONE
        binding.llOtherContacts.visibility = View.GONE
        
        // 保存搜索历史
        saveSearchHistory(searchKey)
        
        // 显示搜索结果
        val searchResults = contactTable.findContactByKey(searchKey)
        otherContactsList.clear()
        specialFavoritesList.clear()
        
        searchResults.forEach { contact ->
            if (contact.name != "无符合条件联系人") {
                if (contact.isFavorite == 1) {
                    specialFavoritesList.add(contact)
                } else {
                    otherContactsList.add(contact)
                }
            }
        }
        applySorting()
        // 在搜索模式下，如果有搜索结果，仍然显示分组
        if (searchResults.isNotEmpty() && searchResults.first().name != "无符合条件联系人") {
            binding.tvSpecialFavorite.text = "常用联系人 (${specialFavoritesList.size})"
            binding.tvSpecialFavorite.visibility = if (specialFavoritesList.isNotEmpty()) View.VISIBLE else View.GONE
            binding.llSpecialFavorites.visibility = if (specialFavoritesList.isNotEmpty()) View.VISIBLE else View.GONE
            
            binding.tvOtherContacts.text = "所有联系人 (${otherContactsList.size})"
            binding.tvOtherContacts.visibility = View.VISIBLE
            binding.llOtherContacts.visibility = View.VISIBLE
            
            setupGroupedListViews()
        } else {
            // 没有搜索结果时的处理
            binding.llOtherContacts.visibility = View.VISIBLE
            otherContactsList.clear()
            val noResultContact = Contact()
            noResultContact.name = "无符合条件联系人"
            otherContactsList.add(noResultContact)
            setupGroupedListViews()
        }
    }
    
    // 打开联系人详情页面
    private fun openContactDetail(contact: Contact) {
        val intent = Intent(this, InfoActivity::class.java)
        intent.putExtra("contact1", contact)
        startActivityForResult(intent, 100)
    }
    
    // 随机选择联系人
    private fun selectRandomContact() {
        // 获取所有联系人列表
        val allContacts = contactTable.findAllContact()
        
        // 过滤掉占位符联系人
        val realContacts = allContacts.filter {
            it.name != "没有联系人" && it.name != "无符合条件联系人"
        }
        
        if (realContacts.isNotEmpty()) {
            // 随机选择一个联系人
            val randomIndex = (0 until realContacts.size).random()
            val randomContact = realContacts[randomIndex]
            
            // 显示随机选择的提示
            Toast.makeText(this, "随机选择了：" + randomContact.name, Toast.LENGTH_SHORT).show()
            openContactDetail(randomContact)
        } else {
            Toast.makeText(this, "没有可选择的联系人", Toast.LENGTH_SHORT).show()
        }
    }
    
    // 保存搜索历史
    private fun saveSearchHistory(keyword: String) {
        if (keyword.isBlank()) return
        
        val history = getSearchHistoryList().toMutableList()
        
        // 如果已存在，则移除旧的
        history.remove(keyword)
        
        // 添加到列表开头
        history.add(0, keyword)
        
        // 保持最大历史记录数量
        if (history.size > MAX_HISTORY_COUNT) {
            history.subList(MAX_HISTORY_COUNT, history.size).clear()
        }
        
        // 保存到SharedPreferences
        val editor = sharedPreferences.edit()
        editor.putStringSet(SEARCH_HISTORY_KEY, history.toSet())
        editor.apply()
        
        // 刷新显示
        loadSearchHistory()
    }
    
    // 加载搜索历史
    private fun loadSearchHistory() {
        val history = getSearchHistoryList()
        
        if (history.isEmpty()) {
            binding.llSearchHistory.visibility = View.GONE
            return
        }
        
        binding.llSearchHistory.visibility = View.VISIBLE
        
        // 设置历史记录文本
        binding.tvHistory1.text = history.getOrNull(0) ?: ""
        binding.tvHistory2.text = history.getOrNull(1) ?: ""
        binding.tvHistory3.text = history.getOrNull(2) ?: ""
        
        // 设置可见性
        binding.tvHistory1.visibility = if (history.size >= 1) View.VISIBLE else View.GONE
        binding.tvHistory2.visibility = if (history.size >= 2) View.VISIBLE else View.GONE
        binding.tvHistory3.visibility = if (history.size >= 3) View.VISIBLE else View.GONE
    }
    
    // 获取搜索历史列表
    private fun getSearchHistoryList(): List<String> {
        return sharedPreferences.getStringSet(SEARCH_HISTORY_KEY, setOf())?.toList() ?: listOf()
    }
    
    // 检查是否有搜索历史
    private fun hasSearchHistory(): Boolean {
        return getSearchHistoryList().isNotEmpty()
    }
    
    // 通过历史记录进行搜索
    private fun searchByHistory(keyword: String) {
        binding.etSearch.setText(keyword)
        binding.etSearch.setSelection(keyword.length)
        showSearchMode(keyword)
    }
    
   
    //张三 腾讯股份有限公司 CEO
    //李四 京东科技有限公司 CTO
    //王五 苹果公司 CTO 17856458970
    //赵六 谷歌公司 CTO 15729805649
    //张大伟 腾讯科技有限公司 CTO 18944592340
    //李二麻  小米科技有限公司 CTO 13874592340
    //王小虎 京东科技有限公司 CEO 15874592340
    //刘逍 阿里巴巴 CEO 15674592340
    //张三丰 腾讯科技有限公司 产品经理 18974592340
    //刘伟
    //曹鸣
    //郭鑫
}